package com.ufpr.bean;

import java.sql.SQLException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import br.com.sebrae.pr.sgp.dao.UsuarioDAO;
import br.com.sebrae.pr.sgp.entities.Usuario;

@ManagedBean
@SessionScoped
public class UserManagedBean extends GenericManagedBean {
//	UserService userService = new UserService();

	// fields
	private String username;
	private String password;

	// getters
	public String getUsername() {
		return username;
	}
	public String getPassword() {
		return password;
	}

	// setters
	public void setUsername(String username) {
		this.username = username;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public void setUsuarioLogado(Usuario usuario) {
		FacesContext context = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
		if (session != null)
			session.setAttribute("usuarioLogado", usuario);
	}

	// public methods
	public String login() {
		FacesContext context = FacesContext.getCurrentInstance();
		try {
			Usuario usuario = new Usuario();
			if (usuario == null) {
				context.addMessage("username", new FacesMessage("Usuário e/ou senha inválidos"));
				return null;
			}
			setUsuarioLogado(usuario);
			return "consertos";
		} catch (Exception e) {
			context.addMessage("username", new FacesMessage("Erro ao realizar login no sistema"));
			e.printStackTrace();
			return null;
		}
	}
	public String limpar() {
		this.username = "";
		password = "";
		return null;
	}
	public String logout() {
		setUsuarioLogado(null);		
		FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
		return "login";
	}
}